package org.example;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class MyThreadPool {
    public   int corePoolSize;
    public  int timeout;
    public TimeUnit timeUnit;
    public int  maxPoolSize;

    //队列慢的时候拒绝策略
    public RejectHandler rejectHandler;

    public MyThreadPool(int corePoolSize, int maxPoolSize, int timeout, TimeUnit timeUnit, ArrayBlockingQueue<Runnable> blockingDeque,RejectHandler rejectHandler) {
        this.corePoolSize = corePoolSize;
        this.timeout = timeout;
        this.timeUnit = timeUnit;
        this.maxPoolSize = maxPoolSize;
        this.blockingDeque=blockingDeque;
        this.rejectHandler=rejectHandler;
    }

     BlockingQueue<Runnable> blockingDeque;

   //核心线程的数量
    List<Thread> coreList=new ArrayList<>();
    //辅助线程的数量
    List<Thread> supportList=new ArrayList<>();

   synchronized void  execute(Runnable command){
       if (coreList.size()<corePoolSize){
           Thread thread = new CoreThead();
           coreList.add(thread);
           thread.start();
       }
       //大于核心线程数直接加入队列里面？
        if (blockingDeque.offer(command)){
            return;
        }
        if (coreList.size()+supportList.size()<maxPoolSize){
                Thread thread=new SupportThread();
                supportList.add(thread);
                thread.start();
        }
        //再次入队失败 直接结束
        if (!blockingDeque.offer(command)){
            rejectHandler.reject(command,this);
        }
    }
     class CoreThead extends Thread{
        @Override
        public void run() {
            while (true){
                try {
                    Runnable take = blockingDeque.take();
                    take.run();;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    class  SupportThread extends  Thread{
        @Override
        public void run() {
            while (true){
                try {
                    Runnable take = blockingDeque.poll(timeout, timeUnit);
                    if (take==null){
                        break;
                    }
                    take.run();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println(Thread.currentThread().getName()+"结束了");
        }
    }
}
